<template>
    <div class="forget">
         <div class="icon">
            <i class="el-icon-s-comment"></i>
        </div>
        <div class="title">
            重置密码
        </div>
        <div class="form">
           <el-form ref="form" :model="form" label-width="60px" :rules="rules">
               <el-form-item label="账号" prop="email">
                    <el-input v-model="form.email" placeholder="请输入您的邮箱"></el-input>
               </el-form-item>
               <el-form-item label="密码" prop="pwd">
                    <el-input v-model="form.pwd" placeholder="请输入新密码"></el-input>
               </el-form-item>
           </el-form>
       </div>
       <div class="code-warp">
           <div class="code">
               <el-input v-model="form.code" placeholder="请输入验证码"></el-input>
           </div>
           <div class="btn" @click.stop="sendCode" ref="codeBtn">
               获取验证码
           </div>
       </div>
       <div class="submit" >
           <el-button type="primary" @click="resetPwd" round>重置密码</el-button>
       </div>
    </div>
</template>
<script lang="ts">
import {Vue,Component} from 'vue-property-decorator'
import axios from 'axios'

@Component
export default class ResetPwd extends Vue{

    $message: any
    $notify: any

    // 表单数据
    public form:any = {
        email: '',
        pwd: '',
        code: ''
    }

    // 数据验证规则
    public rules:any = {
        email:[
            { required: true, trigger: 'change', validator: this.validateEmail }
        ],
        pwd:[
            { required: true, trigger: 'change', validator: this.validatePwd }
        ]
    }
  
    mounted() {
        // 防止用户刷新重置验证码时间
        let codeExpire: string|number = localStorage.getItem('codeExpire') as string
        if(codeExpire != null){
            codeExpire = parseInt(codeExpire)
            const curTime = new Date().getTime()
            if(codeExpire > curTime){
                this.forbigSendCodeBtn(Math.floor((codeExpire - curTime)/1000) + 1)
            }else{
                localStorage.removeItem('codeExpire')
            }
        }
    }

    // 校验邮箱
    private validateEmail(rule:any, value:string, cb:Function){
        if(value.match( /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/g) == null){
            cb(new Error('邮箱格式不正确'))
            return
        }
        cb()
    }

    // 校验密码
    private validatePwd(rule:any, value:string, cb:Function){
        if(value.match(/^\w{6,16}$/g) == null){
            cb(new Error('密码应为6~16位的字母、数字、下划线组成'))
            return
        }
        cb()
    }

    // 禁用发送验证码按钮
    private forbigSendCodeBtn(t:number){
        let time:number = t
        const btn = this.$refs.codeBtn as HTMLElement
        btn.classList.add('forbid')
        btn.innerText = `获取验证码(${time})`
        const timer = setInterval(()=>{
            time -= 1
            btn.innerText = `获取验证码(${time})`
            if(time <= 0){
                btn.classList.remove('forbid')
                btn.innerText = "获取验证码"
                clearInterval(timer)
            }
        },1000)
    }

    // 发送重置密码的验证码
    public sendCode(){
        if(this.form.email == ''){
            this.$message.error("邮箱不能为空")
            return
        }
        this.forbigSendCodeBtn(60)
        const codeExpire = new Date().getTime() + 60 * 1000
        localStorage.setItem("codeExpire", String(codeExpire))
        axios.post("/api/v1/user/forget/" + this.form.email)
            .then(res=>{
                const result = res.data
                if(result.code === 200){
                    this.$notify.success('验证码发送成功')
                }else{
                    this.$notify.error(result.msg)
                }
            }).catch(err=>{
                this.$message.error("发送失败:" + err)
            })
    }

    // 重置密码
    public resetPwd(){
        const {email, pwd, code} = this.form
        if(email.match( /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/g) == null){
            this.$message.error("邮箱格式不正确")
            return
        }
        if(pwd.match(/^\w{6,16}$/) == null){
            this.$message.error("密码应为6~16位的字母、数字、下划线组成")
            return
        }
        if(code.match(/^\d{6}$/) == null){
            this.$message.error("验证码应为6位数字")
            return
        }
        const formData = new FormData()
        formData.append('email', email)
        formData.append('pwd', pwd)
        formData.append('code', code)
        axios.post('/api/v1/user/reset',formData)
            .then(res=>{
                const result = res.data
                if(result.code === 200){
                    this.$notify.success('重置密码成功,3秒后回到登录页。')
                    setTimeout(() => {
                        this.$router.push('/login?email=' + email)
                    }, 3000);
                }else{
                    this.$notify.error(result.msg)
                }
            }).catch(err=>{
                this.$message.error("操作失败:" + err)
            })
    }

}
</script>
<style lang="less" scoped>
@import '../css/index.less';
    .forget{
        .float-win(#fdfdfd);
        .icon{
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 60px;
            color: @theme-color;
        }
        .title{
            text-align: center;
            height: 60px;
            line-height: 60px;
            font-size: 20px;
            color: @theme-color;
       }
       .code-warp{
           display: flex;
           justify-content: space-between;
           align-items: center;
           padding: 10px 0;
           margin-top: -10px;
           .code{
               min-width: 150px;
               flex: 1;
               margin-right: 15px;
           }
           .btn{
               background-color: @theme-color;
               color: white;
               padding: 0 15px;
               height: 40px;
               display: flex;
               justify-content: center;
               align-items: center;
               border-radius: 5px;
               cursor: pointer;
               transition: all 0.5s;
               &:hover{
                   background-color: white;
                   color: @theme-color;
                   border: 1px solid @theme-color;
               }
           }
       }
        .submit{
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 10px;
            button{
                width: 100%;
            }
        }
    }
</style>